const app = getApp()
Page({
  data: {
    countDownVisible: false,
    mobile:'',
    code:''
  },
  onLoad(e){
    //取出到登录页的页面参数
    this.setData({
      redirectURL:e.redirectURL
    })
  },
  countDownChange(ev) {
    this.setData({
      timeData: ev.detail,
      countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0,
    })
  },
   async getCode(){
    if(!this.verifyMobile())return
    if(this.data.countDownVisible)return
    //发送验证码
    try {
      const {data} = await wx.http({
        url:'/code',
        data:{
          mobile:this.data.mobile
        }
      })
      this.setData({
        countDownVisible:true
      })
      wx.utils.toast('发送验证码成功','success')
      setTimeout(() => {
        this.setData({
          code:data.code
        })
      }, 2000);
    } catch (error) {
      console.log(error);
    }
  },
  //检验手机号
  verifyMobile(){
    //检验是否为空
    if(this.data.mobile.trim() == '') return wx.utils.toast('请输入手机号','fail')
    // 宽松的验证规则
    const reg = /^[1][3-8][0-9]{9}$/
    // 正则验证（去除两端空格）
    const valid = reg.test(this.data.mobile.trim())
    // 验证结果提示
    if (!valid) wx.utils.toast('请填写正确的手机号码!','fail')
    // 返回验证结果
    return valid
  },

  // 登录
 async submitForm(){
   //校验输入的手机号和验证码
   if(!this.verifyMobile())return 
   if(!this.data.code)return wx.utils.toast('请输入验证码','fail')
   try {
    const res = await wx.http.post('/login',{
      mobile:this.data.mobile,
      code:this.data.code
     })
    //  console.log(res);
     wx.utils.toast('登录成功','success')
     //持久化token
     wx.setStorageSync('token', res.data.token)
     //全局共享
     app.setToken(res.data.token,res.data.refreshToken) 
     //跳转回上一页
     wx.redirectTo({
       url: `/${this.data.redirectURL}`,
     })
   } catch (error) {
     console.log(error);
   }
  }
})
